package it.polimi.digitalstate.manager;



import it.polimi.digitalstate.dto.CitizenDTO;
import it.polimi.digitalstate.dto.UserDTO;
import it.polimi.digitalstate.entities.Citizen;
import it.polimi.digitalstate.entities.User;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


/**
 * Session Bean implementation class AuthenticationManager
 */
@Stateless
public class AuthenticationManager implements AuthenticationManagerLocal {

	@PersistenceContext
	private EntityManager em;
	
    public AuthenticationManager() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public boolean isLogged() {
		return getUsername() != null;
	}
	private String getUsername(){
		return FacesContext.getCurrentInstance().getExternalContext().getRemoteUser();
	}


	@Override
	public UserDTO getLoggedUser() {
		Query q = em.createNamedQuery("user_getByName");
		System.out.println(getUsername());
		q.setParameter("username", getUsername());
		Object[] res = q.getResultList().toArray();
		if(res.length==0){
			
		}
		if(res.length==1){
			System.out.println(getUsername() + " retreived");
			return ((User)res[0]).getDTO();
			
		}
		//TODO better... throw an exception  :D
		return null;
	}

	@Override
	public CitizenDTO getLoggedCitizen() {
		return getLoggedUser().getCitizen();
		
/*			Query q = em.createNamedQuery("citizen_getByID");
			System.out.println("citizenID=" + getLoggedUser().getCitizen().getID());
			q.setParameter("id", getLoggedUser().getCitizen().getID());
			Object[] res = q.getResultList().toArray();
			if(res.length==0){
				//TODO Throw an Exception
			}
			if(res.length==1){
				return ((Citizen)res[0]).getDTO();
				
			}
			//TODO better... throw an exception  :D
			return null;
*/		
	}

	@Override
	public boolean aCitizenIsLogged() {
		if(isLogged())
			return getLoggedCitizen()!=null;
		return false;
	}
    
}
